package cn.ds.hbase.utils;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Table;

import java.io.IOException;
import java.net.URISyntaxException;


/**
 * 项目名称:hbase-demo<br>
 * 包名:cn.ds.hbase.utils<br>
 * 用于:hbase-demo<br>
 * 创建时间:2019年01月11日<br>
 * 更新时间:2019年01月11日<br>
 *
 * @author :lds（创建人）<br>
 * @version :v1.0（版本号）<br>
 * @since jdk1.8
 */
public class HBsaeConn {

    private static final HBsaeConn INSTANCE = new HBsaeConn();
    private static Configuration configuration;
    private static Connection connection;

    private  HBsaeConn() {
        if (configuration==null){
            configuration = HBaseConfiguration.create();
//            try {
//                configuration.addResource(new Path(ClassLoader.getSystemResource("hbase-site.xml").toURI()));
//                configuration.addResource(new Path(ClassLoader.getSystemResource("core-site.xml").toURI()));
//            } catch (URISyntaxException e) {
//                e.printStackTrace();
//            }
            //"ubuntu:2181"
            configuration.set("hbase.zookeeper.quorum","master:2181,slave1:2181,slave1:2181");
        }
    }

    private synchronized Connection getConnection() throws IOException {
        if (connection==null||connection.isClosed()){
            connection = ConnectionFactory.createConnection(configuration);
        }
        return connection;
    }

    public static Connection getHBaseConn() throws IOException {
        return INSTANCE.getConnection();
    }

    public static Table getTable(String tableName) throws IOException {
        return INSTANCE.getConnection().getTable(TableName.valueOf(tableName));
    }

    public static void closeConn() throws IOException {
        if (connection!=null){
            connection.close();
        }
    }
}
